package com.twotiger.and.activity.account.recharge;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.bean.Bank;
import com.twotiger.and.bean.BankNidList;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.Charge;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.Contact;
import com.twotiger.and.bean.Coupon;
import com.twotiger.and.bean.LLPayResult;
import com.twotiger.and.bean.Order;
import com.twotiger.and.bean.RechargeBank;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.DownPicUtil;
import com.twotiger.and.util.EaseHXUtils;
import com.twotiger.and.util.IntentUtil;
import com.twotiger.and.util.LogUtil;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.URLUtil;
import com.twotiger.and.util.PromptManager.ClickListener;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.util.ViewUtils;
import com.twotiger.and.view.OptionPopupWindow2;
import com.yintong.pay.utils.MobileSecurePayer;

/**
 * @Description: 
 * 连连支付快捷充值 
 * @Author douxy
 * @Date 2015年8月12日 下午1:53:24
 */
public class RechargePage extends BaseActivity implements OnClickListener {

    private SubTitle subTitle;
    private RechargeLayout rechargeLayout;
    /**充值场景*/
    private int chargeScene;

    private List<Bank> bankList;
    private HashMap<String, String> params;
    private OptionPopupWindow2 popup;

    public final static int SCENE_COMMON = 0;
    public final static int SCENE_ORDER = 1; //订单充值
    public final static int SCENE_CURRENT = 2; //活期充值

    private static final int ORDER_OK = 2;
    private static final int ORDER_FAILED = 3;

    private static final int GETHFBANKSUCCES = 5;
    private static final int GETHFBANKFAIL = 6;

    private static final int SENDCHARGE = 7;
    private static final int GETUSERASSERTSUCCES = 8;
    private static final int GETUSERASSERTFAIL = 9;

    private static final int CHARGEHFSUCCESS = 10;
    private static final int CHARGEHFFAIL = 11;

    /**汇付充值各个页面启动标志*/
    public static final int RECHARGEREQUEST = 12;
    /**汇付充值各个页面关闭的标示(充值成功)*/
    public static final int RECHARGERESULTCLOSE_SUC = 13;
    /**汇付充值各个页面关闭的标示(充值失败)*/
    public static final int RECHARGESULTCLOSE_FAI = 14;

    private static final int GETCUNBANKSUCCES = 15;
    private static final int GETCUNBANKFAIL = 16;

    private static final int GETCONTACTSUCCESS = 17;
    private static final int GETCONTACTFAILURE = 18;

    public static final String TAG_CLICK_TELE = "telephone";
    public static final String TAG_CLICK_QQ = "qq";
    private String tag_click; //区分用户是电话联系还是qq联系

    private RechargeBank mRechargeBank; //充值银行卡信息
    private double avlible;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.charge_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        rechargeLayout = new RechargeLayout(view);
        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
                toRechargeTip();
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("充值");
        subTitle.hideBtns();
        subTitle.title_left_bt.setVisibility(View.VISIBLE);
        subTitle.title_right_tv.setText("充值说明");
        subTitle.title_right_tv.setVisibility(View.VISIBLE);
        //不同场景不同布局
        chargeScene = getIntent().getIntExtra("SCENE", SCENE_COMMON);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.tv_unbind_bank:
            PromptManager.showUnbindBankAlert(RechargePage.this, new ReChargeClickListener() {

                @Override
                public void onClickConfirm() {

                }

                @Override
                public void onClickCancel() {

                }
            });
            break;
        case R.id.tv_contact:
            PromptManager.showContactAlert(RechargePage.this, "如有疑问，请联系客服", "电话客服", "在线客服",
                new ClickListener() {

                    @Override
                    public void onClickRight() {
                        tag_click = TAG_CLICK_QQ;
                        //                        getContact();
                        new EaseHXUtils().startEaseChat(RechargePage.this);
                    }

                    @Override
                    public void onClickLeft() {
                        tag_click = TAG_CLICK_TELE;
                        getContact();
                    }
                }, true);
            break;
        case R.id.ll_charge_tip:
            if (mRechargeBank == null) {
                return;
            }
            Intent intent = new Intent(RechargePage.this, WebViewPage.class);
            intent.putExtra("title", "充值");
            Map<String, String> contractmap = new HashMap<String, String>();
            contractmap.put("noticeMethod", mRechargeBank.getNoticeMethod());
            contractmap.put("token", getToken());
            intent.putExtra(
                "url",
                Constants.HOST + Constants.VERSION + "noticeDescHtml?"
                        + URLUtil.createContractUrl(contractmap, "3.0"));
            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.iknow_btn:
            //            rechargeLayout.tips_layout.setVisibility(View.GONE);
            break;
        case R.id.choice_bank:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            hideSoftInputMethod(mContext, rechargeLayout.choice_bank);
            if (bankList == null) {
                getHFbanklist();
            } else {
                //                ArrayList<String> list = new ArrayList<String>();
                //                for (int i = 0; i < bankList.size(); i++) {
                //                    Bank bank = bankList.get(i);
                //                    list.add(bank.getName() + bank.getPerAmt() + "万/笔" + bank.getDayAmt() + "万/日");
                //                }
                popup = new OptionPopupWindow2(mContext, rechargeLayout.choice_bank, bankList);
                //                popup.showAsDropDown(rechargeLayout.charge_ok_button);
                popup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
            break;
        case R.id.charge_ok_button:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            String mChargeMoney = rechargeLayout.charge_amount_et.getText().toString().trim();
            String card = rechargeLayout.input_card_no.getText().toString().trim();
            String banktype = rechargeLayout.choice_bank.getText().toString().trim();
            //            BanklistItem quickBank = getQuickBank();

            try {
                if (StringUtils.isEmpty(mChargeMoney) || Double.parseDouble(mChargeMoney) <= 0) {
                    showToast("请输入充值金额");
                    mChargeMoney = "0.00";
                    return;
                }
                if (mRechargeBank == null) {
                    return;
                }
                if (Double.parseDouble(mChargeMoney) < Double
                    .parseDouble(mRechargeBank.getMinAmt())) {
                    showToast("充值金额需大于最小充值额");
                    return;
                }
                if ("noHFnoLL".equals(mRechargeBank.getMark())) {
                    if (StringUtils.isEmpty(banktype)) {
                        showToast("请先选择充值银行");
                        return;
                    }
                    if (StringUtils.isEmpty(card)) {
                        showToast("请输入银行卡号");
                        return;
                    }
                    if (popup != null) {
                        if (Double.parseDouble(mChargeMoney) > Double.parseDouble(ArithUtils.mul(
                            bankList.get(popup.getselectpositon()).getPerAmt(), 10000 + ""))) {
                            PromptManager.showContactAlert(RechargePage.this,
                                "由于银行卡限制\n单笔最大充值："
                                        + bankList.get(popup.getselectpositon()).getPerAmt()
                                        + "万\n大额充值请登录两只老虎官网www.twotiger.com用网银进行充值。", "我知道了", "",
                                new ClickListener() {

                                    @Override
                                    public void onClickRight() {

                                    }

                                    @Override
                                    public void onClickLeft() {

                                    }
                                }, false);
                            return;
                        }
                        checkNoCardPay(bankList.get(popup.getselectpositon()).getNoCardPay(),
                            ArithUtils.coverMoney(mChargeMoney), card,
                            bankList.get(popup.getselectpositon()).getNid());
                    }
                } else if ("haveHF".equals(mRechargeBank.getMark())) {
                    if (Double.parseDouble(mChargeMoney) > Double.parseDouble(ArithUtils.mul(
                        mRechargeBank.getPerAmt(), 10000 + ""))) {
                        PromptManager.showContactAlert(RechargePage.this,
                            "由于银行卡限制\n单笔最大充值：" + mRechargeBank.getPerAmt()
                                    + "万\n大额充值请登录两只老虎官网www.twotiger.com用网银进行充值。", "我知道了", "",
                            new ClickListener() {

                                @Override
                                public void onClickRight() {

                                }

                                @Override
                                public void onClickLeft() {

                                }
                            }, false);
                        return;
                    }
                    checkNoCardPay(mRechargeBank.getNoCardPay(),
                        ArithUtils.coverMoney(mChargeMoney), mRechargeBank.getCardNo(),
                        mRechargeBank.getNid());
                } else if ("haveLLhaveHF".equals(mRechargeBank.getMark())) {
                    if (Double.parseDouble(mChargeMoney) > Double.parseDouble(ArithUtils.mul(
                        mRechargeBank.getPerAmt(), 10000 + ""))) {
                        PromptManager.showContactAlert(RechargePage.this,
                            "由于银行卡限制\n单笔最大充值：" + mRechargeBank.getPerAmt()
                                    + "万\n大额充值请登录两只老虎官网www.twotiger.com用网银进行充值。", "我知道了", "",
                            new ClickListener() {

                                @Override
                                public void onClickRight() {

                                }

                                @Override
                                public void onClickLeft() {

                                }
                            }, false);
                        return;
                    }
                    PromptManager.showConfirmAlertChargeUpgrade(mContext,
                        new ReChargeClickListener() {

                            @Override
                            public void onClickConfirm() {
                                checkNoCardPay(
                                    mRechargeBank.getNoCardPay(),
                                    ArithUtils.coverMoney(rechargeLayout.charge_amount_et.getText()
                                        .toString().trim()), mRechargeBank.getCardNo(),
                                    mRechargeBank.getNid());
                            }

                            @Override
                            public void onClickCancel() {

                            }
                        });

                } else if ("haveLLnoHFopenLL".equals(mRechargeBank.getMark())) {
                    if (Double.parseDouble(mChargeMoney) > Double.parseDouble(ArithUtils.mul(
                        mRechargeBank.getPerAmt(), 10000 + ""))) {
                        PromptManager.showContactAlert(RechargePage.this,
                            "由于银行卡限制\n单笔最大充值：" + mRechargeBank.getPerAmt()
                                    + "万\n大额充值请登录两只老虎官网www.twotiger.com用网银进行充值。", "我知道了", "",
                            new ClickListener() {

                                @Override
                                public void onClickRight() {

                                }

                                @Override
                                public void onClickLeft() {

                                }
                            }, false);
                        return;
                    }
                    charge(ArithUtils.coverMoney(mChargeMoney), mRechargeBank.getCardNo(),
                        mRechargeBank.getNid());
                } else if ("haveLLnoHFcolseLL".equals(mRechargeBank.getMark())) {
                    if (StringUtils.isEmpty(banktype)) {
                        showToast("请先选择充值银行");
                        return;
                    }
                    if (StringUtils.isEmpty(card)) {
                        showToast("请输入银行卡号");
                        return;
                    }
                    if (popup != null) {
                        if (Double.parseDouble(mChargeMoney) > Double.parseDouble(ArithUtils.mul(
                            bankList.get(popup.getselectpositon()).getPerAmt(), 10000 + ""))) {
                            PromptManager.showContactAlert(RechargePage.this,
                                "由于银行卡限制\n单笔最大充值："
                                        + bankList.get(popup.getselectpositon()).getPerAmt()
                                        + "万\n大额充值请登录两只老虎官网www.twotiger.com用网银进行充值。", "我知道了", "",
                                new ClickListener() {

                                    @Override
                                    public void onClickRight() {

                                    }

                                    @Override
                                    public void onClickLeft() {

                                    }
                                }, false);
                            return;
                        }
                        checkNoCardPay(bankList.get(popup.getselectpositon()).getNoCardPay(),
                            ArithUtils.coverMoney(mChargeMoney), card,
                            bankList.get(popup.getselectpositon()).getNid());
                    }
                }

            } catch (Exception e) {
                LogUtil.info(String.valueOf(e.getMessage()));
            }
            break;

        case R.id.rl_useotherbank:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            String mCMoney = rechargeLayout.charge_amount_et.getText().toString().trim();
            if (StringUtils.isEmpty(mCMoney) || Double.parseDouble(mCMoney) < 0) {
                showToast("请输入充值金额");
                mChargeMoney = "0.00";
                return;
            }
            PromptManager.showConfirmAlertCharge(mContext, (ArrayList<Bank>) bankList,
                new ReChargeClickListener() {

                    @Override
                    public void onClickConfirm() {
                        chargeHF(
                            ArithUtils.coverMoney(rechargeLayout.charge_amount_et.getText()
                                .toString().trim()), "", "");
                    }

                    @Override
                    public void onClickCancel() {

                    }
                });
            break;
        }
    }

    /**
     * 获取客服电话和客服qq
     */
    protected void getContact() {
//        params.clear();
//        getDate(params, Constants.constant_query, handler, GETCONTACTSUCCESS, GETCONTACTFAILURE,
//            true, false, false);
        
        if (TAG_CLICK_TELE.equals(tag_click)) {
            ConstantDataUnit cl_kfdh = getConstantDataByKey(Constants.cl_kfdh);
            if(cl_kfdh != null){
                String telNum = cl_kfdh.getVal();
                IntentUtil.CallPhone(RechargePage.this, telNum);
            }
        } else if (TAG_CLICK_QQ.equals(tag_click)) {
            
        }
    }

    /**
     * 判断是否需要弹窗无卡支付
     * 
     * @param bank
     */
    private void checkNoCardPay(String noCardPay, final String chargeMoney, final String card,
                                final String nid) {

        if ("1".equals(noCardPay)) { //需要开通无卡支付，弹窗提示
            PromptManager.showBankLimitAlert(RechargePage.this, new ReChargeClickListener() {

                @Override
                public void onClickConfirm() {
                    chargeHF(chargeMoney, card, nid);
                }

                @Override
                public void onClickCancel() {

                }
            });
        } else if ("0".equals(noCardPay)) { //不需要
            chargeHF(chargeMoney, card, nid);
        }
    }

    /**
     * 充值
     * @param chargeMoney
     * @param card
     */

    @Override
    protected void onResume() {
        getuserAssert();
        super.onResume();
    }

    private void getuserAssert() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.ASSETQUERY, handler, GETUSERASSERTSUCCES, GETUSERASSERTFAIL,
            false, true, false);
    }

    private void chargeHF(String chargeMoney, String card, String nid) {
        params = getParm();
        params.clear();
        params.put("token", getToken());
        params.put("amount", ArithUtils.coverMoney(chargeMoney));
        if (!"".equals(nid)) {
            params.put("bankNid", nid);
        }
        if (!"".equals(card)) {
            params.put("cardNo", card);
        }
        getDate(params, Constants.RECHARGEHF, handler, CHARGEHFSUCCESS, CHARGEHFFAIL, true, true,
            false);
    }

    private void charge(String chargeMoney, String card, String nid) {
        params = getParm();
        params.clear();
        params.put("token", getToken());
        params.put("amount", ArithUtils.coverMoney(chargeMoney));
        params.put("bankNid", nid);
        params.put("cardNo", card);
        getDate(params, Constants.RECHARGE, handler, ORDER_OK, ORDER_FAILED, true, true, false);
    }

    //    /**
    //     * 支持的银行卡列表（连连银行卡标识）
    //     */
    //    private void getLLbanklist() {
    //        params.clear();
    //        params.put("token", getToken());
    //        getDate(params, Constants.BANKNIDQUERY, handler, GETBANKSUCCES, GETBANKFAIL, true, false, false);
    //    }
    /**
     * 支持的银行卡列表（汇付银行卡标识）
     */
    private void getHFbanklist() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.BANKNIDHFQUERY, handler, GETHFBANKSUCCES, GETHFBANKFAIL, true,
            false, false);
    }

    @Override
    protected void setListener() {
        rechargeLayout.setOnclickListener(this);
        handler = new BaseHandler(this) {
            private Charge charge;

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETCONTACTSUCCESS:
                    Contact mContact = JSONObject.parseObject((String) msg.obj, Contact.class);
                    if (mContact.isOk()) {
                        if (TAG_CLICK_TELE.equals(tag_click)) {
                            String telNum = mContact.getTelNum();
                            IntentUtil.CallPhone(RechargePage.this, telNum);
                        } else if (TAG_CLICK_QQ.equals(tag_click)) {

                            String qqServUrl = mContact.getQqServUrl();
                            String qqType = mContact.getQqType();

                            if ("personal".equals(qqType)) { //需根据时间判断是否弹窗
                                String timeNow = TimeUtils.getFormatTime1();
                                String qqServTime = mContact.getQqServTime();
                                String[] timeArray = qqServTime.split("-");
                                int nowTimeToMinute = TimeUtils.timeToMinute(timeNow);
                                int qqServTimePreToMinute = TimeUtils.timeToMinute(timeArray[0]);
                                int qqServTimeEndToMinute = TimeUtils.timeToMinute(timeArray[1]);
                                if (nowTimeToMinute < qqServTimePreToMinute
                                    || nowTimeToMinute > qqServTimeEndToMinute) {
                                    PromptManager.showContactAlert(RechargePage.this,
                                        "工作时间：" + qqServTime + "\n请在工作时间联系哦", "我知道了", "",
                                        new ClickListener() {

                                            @Override
                                            public void onClickRight() {
                                            }

                                            @Override
                                            public void onClickLeft() {
                                            }
                                        }, false);
                                } else { //直接进入聊天，无需再根据时间判断是否弹窗
                                    Intent intent = new Intent(Intent.ACTION_VIEW,
                                        Uri.parse(qqServUrl));
                                    if (IntentUtil.queryIntentActivities(RechargePage.this, intent)) {
                                        startNewActivity(intent, R.anim.push_left_in,
                                            R.anim.push_left_out, false);
                                    } else {
                                        showToast("您的手机还未安装QQ,请先下载QQ");
                                    }
                                }
                            } else { //直接进入聊天，无需再根据时间判断是否弹窗
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(qqServUrl));
                                if (IntentUtil.queryIntentActivities(RechargePage.this, intent)) {
                                    startNewActivity(intent, R.anim.push_left_in,
                                        R.anim.push_left_out, false);
                                } else {
                                    showToast("您的手机还未安装QQ,请先下载QQ");
                                }
                            }
                        }
                    } else {
                        showToast(mContact.codeDesc);
                    }
                    break;
                case GETCONTACTFAILURE:
                    showToast("网络异常");
                    break;
                case ORDER_OK:
                    Basebean result_ll = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_ll.isOk()) {// 成功
                        charge = JSON.parseObject(result_ll.data, Charge.class);
                        MobileSecurePayer ll = new MobileSecurePayer();
                        ll.pay(charge.getLLMessage(), handler, SENDCHARGE, RechargePage.this);
                    } else {
                        PromptManager.showConfirmAlertCommon(RechargePage.this, 0,
                            "", charge.codeDesc, "确认", "", false, new ReChargeClickListener() {

                                @Override
                                public void onClickConfirm() {

                                }

                                @Override
                                public void onClickCancel() {

                                }
                            });

                    }
                    break;
                case CHARGEHFSUCCESS:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        BroswerUrl url = JSON.parseObject(result.data, BroswerUrl.class);
                        Intent intent = new Intent(RechargePage.this, WebViewPage.class);
                        intent.putExtra("url", url.getUrl());
                        intent.putExtra("title", "充值");
                        intent.putExtra("SHOWPASSWORD", "showPassword");
                        switch (chargeScene) {
                        case SCENE_COMMON:
                            intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_RECHARGE_HF_DERECT);
                            break;
                        case SCENE_CURRENT:
                            intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_RECHARGE_HF_ORDER);
                            break;
                        case SCENE_ORDER:
                            intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_RECHARGE_HF_ORDER);
                            break;
                        default:
                            break;
                        }
                        startNewActivityforresult(intent, R.anim.push_left_in,
                            R.anim.push_left_out, RECHARGEREQUEST);
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case CHARGEHFFAIL:
                    showToast("网络异常");
                    break;
                case GETHFBANKSUCCES:
                    Basebean result_hf = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_hf.isOk()) {
                        BankNidList list = JSON.parseObject(result_hf.data, BankNidList.class);
                        bankList = JSON.parseArray(list.getBankNidHFList(), Bank.class);
                    } else {
                        showToast(result_hf.codeDesc);
                    }
                    break;
                case GETHFBANKFAIL:

                    break;
                case GETUSERASSERTSUCCES:
                    Basebean result_1 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_1.isOk()) {
                        UserAsset userAsset = JSON.parseObject(result_1.data, UserAsset.class);
                        avlible = userAsset.avaliable;
                        rechargeLayout.setAvaliable(userAsset.avaliable);

                        switch (chargeScene) {
                        case SCENE_CURRENT: //活期订单充值的情况，需要填充输入框金额
                            String currentAmount = getIntent().getStringExtra("CURRENT_AMOUNT");
                            rechargeLayout.current(currentAmount, avlible);
                            break;
                        }
                    } else {
                        showToast(result_1.codeDesc);
                    }
                    break;
                case GETUSERASSERTFAIL:

                    break;
                case SENDCHARGE: //回调获取连连支付返回的充值信息字符串
                    String chargeResult = (String) msg.obj;
                    LogUtil.info(RechargePage.class, chargeResult);
                    LLPayResult payResult = JSON.parseObject(chargeResult, LLPayResult.class);
                    if (com.yintong.pay.utils.Constants.RESULT_PAY_SUCCESS.equals(payResult
                        .getResult_pay())) {
                        PromptManager.showConfirmAlert2(RechargePage.this, 0,
                            "充值成功", "任性投资去吧", "继续投资", "", false, new ReChargeClickListener() {

                                @Override
                                public void onClickConfirm() {
                                    RechargePage.this.finish();
                                }

                                @Override
                                public void onClickCancel() {

                                }
                            });
                    } else {
                        String mes_error = null;
                        if ("1004".equals(payResult.getRet_code())) {
                            mes_error = "银行卡信息和您认证信息不符";
                        } else {
                            mes_error = payResult.getRet_msg();
                        }
                        PromptManager.showConfirmAlert2(RechargePage.this, 0, "充值失败",
                            mes_error, "再试一次", "算了吧", true, new ReChargeClickListener() {

                                @Override
                                public void onClickConfirm() { //再试一次
                                    MobileSecurePayer ll = new MobileSecurePayer();
                                    ll.pay(charge.getLLMessage(), handler, SENDCHARGE,
                                        RechargePage.this);

                                }

                                @Override
                                public void onClickCancel() { //算了吧

                                }
                            });
                        //                        showToast(payResult.getRet_msg());
                    }
                    break;
                case GETCUNBANKSUCCES:
                    Basebean result_b = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_b.isOk()) {
                        mRechargeBank = JSON.parseObject(result_b.data, RechargeBank.class);
                        showDifferenceLayout();
                    } else {
                        showToast(result_b.codeDesc);
                    }
                    break;
                case GETCUNBANKFAIL:

                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        super.onActivityResult(requestcode, resultcode, intent);
        if (requestcode == RECHARGEREQUEST) {
            if (resultcode == RECHARGERESULTCLOSE_SUC) {
                finish();
            }
        }
    }

    @Override
    protected void processLogic() {
        params = getParm();
        initPage();
        initData();
    }

    class downloadImageTask extends AsyncTask<String, Integer, Boolean> {

        private Bitmap bankLogo;

        @Override
        protected Boolean doInBackground(String... params) {
            bankLogo = DownPicUtil.getNetWorkBitmap(params[0]);
            return true;
        }

        // 下载完成回调
        @Override
        protected void onPostExecute(Boolean result) {
            rechargeLayout.setBankIcon(bankLogo);
            super.onPostExecute(result);
        }

        // 更新进度回调
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

    }

    /**
     * 获取充值银行卡列表
     */
    private void getchargebankcards() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.RECHARGEBANKQUERY, handler, GETCUNBANKSUCCES, GETCUNBANKFAIL,
            true, true, false);
    }

    private void initPage() {
        avlible = getIntent().getDoubleExtra("CHARGE", 0.00d);
        rechargeLayout.setAvaliable(avlible);
        mRechargeBank = (RechargeBank) getIntent().getSerializableExtra("RECHARGEBANK");

        if (mRechargeBank == null) {
            getchargebankcards();
        }

        showDifferenceLayout();

        switch (chargeScene) {
        case SCENE_CURRENT:

            String currentAmount = getIntent().getStringExtra("CURRENT_AMOUNT");
            rechargeLayout.current(currentAmount, avlible);
            break;
        case SCENE_COMMON:
            rechargeLayout.common();
            break;
        case SCENE_ORDER:
            Order order = (Order) getIntent().getSerializableExtra("ORDER");
            Coupon coupon = (Coupon) getIntent().getSerializableExtra("COUPON");
            rechargeLayout.order(order, coupon);
            break;
        default:
            break;
        }
    }

    private void showDifferenceLayout() {
        if (mRechargeBank == null) {
            return;
        }
        if ("true".equals(mRechargeBank.getIsHFQuickCard())) {
            rechargeLayout.isShowUnbindBtn(true);
        } else if ("false".equals(mRechargeBank.getIsHFQuickCard())) {
            rechargeLayout.isShowUnbindBtn(false);
        }
        if ("noHFnoLL".equals(mRechargeBank.getMark())) {
            rechargeLayout.first(mRechargeBank);
        } else if ("haveHF".equals(mRechargeBank.getMark())) {
            new downloadImageTask() {
            }.execute(Constants.HOST + mRechargeBank.getBankLogo());
            rechargeLayout.nonFirst(mRechargeBank);
        } else if ("haveLLhaveHF".equals(mRechargeBank.getMark())) {
            new downloadImageTask() {
            }.execute(Constants.HOST + mRechargeBank.getBankLogo());
            rechargeLayout.nonFirst(mRechargeBank);
        } else if ("haveLLnoHFopenLL".equals(mRechargeBank.getMark())) {
            new downloadImageTask() {
            }.execute(Constants.HOST + mRechargeBank.getBankLogo());
            rechargeLayout.nonFirst(mRechargeBank);
            rechargeLayout.showOtherButton();
        } else if ("haveLLnoHFcolseLL".equals(mRechargeBank.getMark())) {
            rechargeLayout.first(mRechargeBank);
            rechargeLayout.showChargeUptip(mRechargeBank.getNoticeMsg());
        } else {
            rechargeLayout.first(mRechargeBank);
        }
    }

    private void initData() {
        getHFbanklist();
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    private void toRechargeTip() {
        ConstantDataUnit czsm = getConstantDataByKey(Constants.dz_czsm);
        if(czsm != null){
            Intent intent = new Intent(mContext, WebViewPage.class);
            intent.putExtra("url", czsm.getVal());
            intent.putExtra("title", "充值");
            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
        }
    }
}
